﻿// Fill out your copyright notice in the Description page of Project Settings.


#include "SmartObjectExtensions.h"
#include "IImageWrapper.h"
#include "IImageWrapperModule.h"
#include "ObjectTools.h"
#include "Misc/FileHelper.h"


TSharedPtr<IImageWrapper> USmartObjectExtensions::GetImageWrapperByExtention(FString OutPath)
{
	IImageWrapperModule& ImageWrapperModule = FModuleManager::LoadModuleChecked<IImageWrapperModule>(FName("ImageWrapper"));
	if (OutPath.EndsWith(".png"))
	{
		return ImageWrapperModule.CreateImageWrapper(EImageFormat::PNG);
	}
	else if (OutPath.EndsWith(".jpg"))
	{
		return ImageWrapperModule.CreateImageWrapper(EImageFormat::JPEG);
	}
	else if (OutPath.EndsWith(".bmp"))
	{
		return ImageWrapperModule.CreateImageWrapper(EImageFormat::BMP);
	}
	else if (OutPath.EndsWith(".exr"))
	{
		return ImageWrapperModule.CreateImageWrapper(EImageFormat::EXR);
	} else
	{
		return nullptr;
	}
}

bool USmartObjectExtensions::SmRenderThumbnail(UObject* Object, FString OutPath, int32 Width, int32 Height)
{
	FObjectThumbnail ObjectThumbnail;
	ThumbnailTools::RenderThumbnail(Object, Width, Height, ThumbnailTools::EThumbnailTextureFlushMode::AlwaysFlush, NULL, &ObjectThumbnail);
	TArray<uint8> MetaData = ObjectThumbnail.GetUncompressedImageData();

	TArray<FColor> ImageRawColor;
	for(int i = 0; i< MetaData.Num(); i += 4)
	{
		ImageRawColor.Add(FColor(MetaData[i+2], MetaData[i+1], MetaData[i], MetaData[i+3]));
	}
	TSharedPtr<IImageWrapper> ImageWrapper =GetImageWrapperByExtention(OutPath);
	if(ImageWrapper.IsValid())
	{
		ImageWrapper->SetRaw(ImageRawColor.GetData(), ImageRawColor.GetAllocatedSize(), Width, Height, ERGBFormat::RGBA, 8);
		return FFileHelper::SaveArrayToFile(ImageWrapper->GetCompressed(100), *OutPath);
	}
	return false;
}

bool USmartObjectExtensions::SmExportThumbnail(UObject* Object, FString OutPath)
{
	FObjectThumbnail ObjectThumbnail;
	if(ThumbnailTools::AssetHasCustomThumbnail(Object->GetFullName(), ObjectThumbnail))
	{
		TArray<uint8> MetaData = ObjectThumbnail.GetUncompressedImageData();
		TArray<FColor> ImageRawColor;
		for(int i = 0; i< MetaData.Num(); i += 4)
		{
			// ImageRawColor.Add(FColor(MetaData[i+2], MetaData[i+1], MetaData[i], MetaData[i+3]));
			ImageRawColor.Add(FColor(MetaData[i+2], MetaData[i+1], MetaData[i]));
		}
		TSharedPtr<IImageWrapper> ImageWrapper =GetImageWrapperByExtention(OutPath);

		if(ImageWrapper.IsValid())
		{
			ImageWrapper->SetRaw(ImageRawColor.GetData(), ImageRawColor.GetAllocatedSize(), ObjectThumbnail.GetImageWidth(), ObjectThumbnail.GetImageHeight(), ERGBFormat::RGBA, 8);
			return FFileHelper::SaveArrayToFile(ImageWrapper->GetCompressed(100), *OutPath);
		}
	}
	return false;
}

